<template>
  <view class="consult-list-page">
    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view 
        v-for="tab in dynamicFilterTabs" 
        :key="tab.value"
        class="filter-tab"
        :class="{ active: activeFilter === tab.value }"
        @click="switchFilter(tab.value)"
      >
        <text class="tab-text">{{ tab.label }}</text>
      </view>
    </view>
    <!-- 咨询列表 -->
    <Loader :loading="loading">
      <scroll-view class="consult-list" scroll-y refresher-enabled :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh" @scroll="handleScroll" refresher-background="#f5f5f5">
        <view v-for="consult in consultList" :key="consult.id" class="consult-item"
          @click="goToConsultDetail(consult.id)">
          <view class="consult-header">
            <view class="consult-title-section">
              <view class="question-type-tags">
                <view 
                  v-for="type in getQuestionTypeLabels(consult.question_types)" 
                  :key="type"
                  class="question-type-tag"
                >
                  <text class="tag-text">{{ type }}</text>
                </view>
              </view>
            </view>
            <view class="consult-status" :class="getStatusClass(consult.status)">
              <text class="status-text">{{ getStatusText(consult.status) }}</text>
            </view>
          </view>

          <view class="consult-content">
            <text class="consult-description">{{ consult.description }}</text>
          </view>

          <view class="consult-footer">
            <text class="consult-date">{{ formatDate(consult.created_at) }}</text>
            <view class="consult-type-tags">
              <view 
                v-for="type in getQuestionTypeLabels(consult.question_types)" 
                :key="type"
                class="consult-type-tag"
              >
                <text class="type-tag-text">{{ type }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-if="consultList.length === 0 && !loading" class="empty-state">
          <!-- <image class="empty-icon" src="/static/icon/empty.svg" /> -->
          <text class="empty-text">暂无咨询</text>
        </view>
      </scroll-view>
    </Loader>

    <!-- 创建咨询悬浮按钮 -->
    <view class="fab-button" @click="createConsult">
      <!-- <image class="fab-icon" src="/static/icon/add.svg" /> -->
      <text class="fab-text">新建咨询</text>
    </view>
  </view>
</template>

<script>
import Loader from '@/components/Loader/Loader.vue'
import consultConfig from '@/static/config/consult_config.json'

export default {
  name: "UserConsultList",
  components: { Loader },
  data() {
    return {
      consultList: [],
      loading: false,
      refreshing: false,
      currentPage: 0,
      batchSize: 10,
      totalNum: 0,
      activeFilter: 'all',
      filterTabs: [
        { value: 'all', label: '全部' },
        { value: 1, label: '待认领' },
        { value: 2, label: '进行中' },
        { value: 3, label: '已解决' }
      ]
    };
  },
  computed: {
    dynamicFilterTabs() {
      return [
        { value: 'all', label: '全部' },
        { value: 1, label: this.getStatusText(1) },
        { value: 2, label: this.getStatusText(2) },
        { value: 3, label: this.getStatusText(3) }
      ];
    }
  },
  methods: {
    // 获取问题类型标签数组
    getQuestionTypeLabels(questionTypes) {
      if (!questionTypes || !Array.isArray(questionTypes)) {
        return ['未分类'];
      }
      
      // 根据配置映射中文标签
      const typeLabels = questionTypes.map(type => {
        if (consultConfig && consultConfig.question_types && consultConfig.question_types[type]) {
          return consultConfig.question_types[type].cn;
        }
        return type; // 如果配置中没有找到，返回原值
      }).filter(label => label);
      
      return typeLabels.length > 0 ? typeLabels : ['未分类'];
    },
    
    // 切换筛选条件
    switchFilter(filter) {
      if (this.activeFilter === filter) return;
      this.activeFilter = filter;
      // 重置分页与列表
      this.consultList = [];
      this.currentPage = 0;
      this.totalNum = 0;
      // 重新加载
      this.loadConsultList();
    },
    // 获取咨询列表
    async loadConsultList() {
      if (this.loading) return;
      this.loading = true;

      try {
        const requestData = {
          batch_num: this.currentPage,
          batch_size: this.batchSize
        };
        if (this.activeFilter !== 'all') {
          requestData.status = this.activeFilter;
        }

        const response = await this.$request({
          url: '/consultation/tickets/user/get/',
          method: 'GET',
          data: requestData
        });

        if (response.statusCode === 200) {
          const { tickets, total_num } = response.data;
          this.totalNum = total_num;

          // 直接使用原始数据，问题类型在模板中处理
          const processedTickets = tickets;

          this.consultList = this.consultList.concat(processedTickets);
          this.currentPage++;
        } else {
          console.error('获取咨询列表失败:', response);
          uni.showToast({
            title: '获取咨询列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取咨询列表失败:', error);
        uni.showToast({
          title: '获取咨询列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 跳转到咨询详情
    goToConsultDetail(consultId) {
      uni.navigateTo({
        url: `/sub_pages/pages/consult_detail/consult_detail?ticketId=${consultId}`
      });
    },

    // 创建咨询
    createConsult() {
      uni.navigateTo({
        url: '/sub_pages/pages/consult_create/consult_create'
      });
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusMap = {
        1: 'status-seeking',    // 寻找专家
        2: 'status-progress',   // 解决中
        3: 'status-resolved'    // 已解决
      };
      return statusMap[status] || 'status-default';
    },
    
    // 获取状态文本
    getStatusText(status) {
      if (consultConfig && consultConfig.ticket_status && consultConfig.ticket_status[status]) {
        return consultConfig.ticket_status[status];
      }
      return '未知状态';
    },

    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },

    // 滚动处理
    handleScroll(e) {
      const { scrollTop, scrollHeight } = e.detail;
      const threshold = 100; // 距离底部100rpx时触发加载

      // 判断是否接近底部
      if (scrollHeight - scrollTop <= threshold + 500) {
        if (this.consultList.length < this.totalNum && !this.loading) {
          this.loadConsultList();
        }
      }
    },

    // 下拉刷新
    onRefresh() {
      if (this.refreshing) return;
      this.refreshing = true;

      // 重置数据
      this.consultList = [];
      this.currentPage = 0;
      this.totalNum = 0;

      // 重新加载数据
      this.$request({
        url: '/consultation/tickets/user/get/',
        method: 'GET',
        data: {
          batch_num: 0,
          batch_size: this.batchSize,
          ...(this.activeFilter !== 'all' ? { status: this.activeFilter } : {})
        },
        success: (response) => {
          if (response.statusCode === 200) {
            const { tickets, total_num } = response.data;
            this.totalNum = total_num;

            // 直接使用原始数据，问题类型在模板中处理
            const processedTickets = tickets;

            this.consultList = processedTickets;
            this.currentPage = 1;

            uni.showToast({
              title: '刷新成功',
              icon: 'success',
              duration: 1500
            });
          } else {
            console.error('刷新咨询列表失败');
            uni.showToast({
              title: '刷新失败',
              icon: 'none',
              duration: 1500
            });
          }
          this.refreshing = false;
        },
        fail: (error) => {
          console.error('刷新请求失败', error);
          uni.showToast({
            title: '刷新失败',
            icon: 'none',
            duration: 1500
          });
          this.refreshing = false;
        }
      });
    }
  },

  onLoad() {
    this.loadConsultList();
  },

  onShow() {
    // 页面显示时刷新列表（如果列表为空）
    if (this.consultList.length === 0) {
      this.loadConsultList();
    }
  }
};
</script>

<style scoped>
.consult-list-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.filter-tabs {
  display: flex;
  background: white;
  border-radius: 16rpx;
  padding: 8rpx;
  margin: 20rpx 0;
  gap: 8rpx;
}

.filter-tab {
  flex: 1;
  padding: 16rpx 0;
  text-align: center;
  border-radius: 12rpx;
  transition: all 0.3s;
}

.filter-tab.active {
  background-color: #007bff;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
}

.filter-tab.active .tab-text {
  color: white;
  font-weight: bold;
}

.page-header {
  padding: 20rpx 0;
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.consult-list {
  margin-top: 20rpx;
  height: calc(100vh - 200rpx);
}

.consult-item {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.consult-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.consult-title-section {
  flex: 1;
}

.question-type-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
}

.question-type-tag {
  background-color: #e7f3ff;
  color: #007bff;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
}

.tag-text {
  font-size: 24rpx;
  color: #007bff;
}

.consult-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  margin-left: 20rpx;
}

.status-seeking {
  background-color: #fff3cd;
  color: #856404;
}

.status-progress {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-resolved {
  background-color: #d4edda;
  color: #155724;
}

.status-text {
  font-size: 24rpx;
}

.consult-content {
  margin-bottom: 20rpx;
}

.consult-description {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.consult-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.consult-date {
  font-size: 24rpx;
  color: #999;
}

.consult-type-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6rpx;
}

.consult-type-tag {
  background-color: #f8f9fa;
  color: #666;
  padding: 4rpx 8rpx;
  border-radius: 8rpx;
  font-size: 20rpx;
}

.type-tag-text {
  font-size: 20rpx;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.fab-button {
  position: fixed;
  right: 36rpx;
  bottom: 40rpx;
  background-color: #F26A77;
  color: #FFFFFF;
  padding: 20rpx 28rpx;
  border-radius: 9999rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

.fab-text {
  font-size: 28rpx;
  color: #FFFFFF;
}
</style>
